//
//  ViewController.m
//  KIASupervisory
//
//  Created by tan_xin on 14-6-27.
//  Copyright (c) 2014年 eKing. All rights reserved.
//

#import "LoginViewController.h"

#import "DDMenuController.h"
#import "FindPasswordViewController.h"

#import "LeaderLeftMenuViewController.h"
#import "ErandApproveListViewController.h"

#import "DuDaoLeftMenuController.h"
#import "MainViewController.h"
#import "Reg1ViewController.h"
#import "ErandDudaoListByDayViewController.h"
#import "UserInfo.h"

#import "UIDevice+IdentifierAddition.h"
#import "KeychainItemWrapper.h"
#import "YoukeViewController.h"

@interface LoginViewController () <UIGestureRecognizerDelegate>

@property (weak, nonatomic) IBOutlet UIView *contentView;
@property (weak, nonatomic) IBOutlet UITextField *userNameTf;
@property (weak, nonatomic) IBOutlet UITextField *passwordTf;

@property (nonatomic, assign) CGRect contentPreFrame;

- (IBAction)goToFindBackPasswordAction:(id)sender;
- (IBAction)loginAction:(id)sender;
- (IBAction)didFinishedEditAction:(id)sender;

@end

@implementation LoginViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

	// Do any additional setup after loading the view, typically from a nib.
   
    [self initHUD];
    [self addKeyboardNotificationForTarget:self];
    
    CGRect frame = self.contentView.frame;
    NSLog(@"*********pre frame:%@",NSStringFromCGRect(self.contentView.frame));
    self.contentPreFrame = frame;
    
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
    tapGesture.numberOfTapsRequired = 1;
    tapGesture.delegate = self;
    
    [self.view addGestureRecognizer:tapGesture];
   // [self versionCheck];
    
//    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    if ([defaults objectForKey:@"username"]) {
        self.userNameTf.text = [defaults objectForKey:@"username"];
    }
    if ([defaults objectForKey:@"password"]) {
        self.passwordTf.text = [defaults objectForKey:@"password"];
    }
    NSUserDefaults *userDefaultes = [NSUserDefaults standardUserDefaults];
 
    NSString *usernameObj = [userDefaultes stringForKey:@"username"];
    NSString *pwdObj = [userDefaultes stringForKey:@"pwd"];
  
    
    if(usernameObj != nil && pwdObj != nil){
        if (self.networkManager == nil) {
            self.networkManager = [[NetworkManager alloc] init];
        }
       NSMutableDictionary *param = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                                     usernameObj,@"phone",
                                      pwdObj,@"pwd", nil];

        if (param != nil) {
            [self.networkManager requestWithMethod:login parameter:param delegate:self];
            [self.HUD show:YES];
        }
    }
    
    
}

- (void)tapAction:(UIGestureRecognizer *)recognizer {
    [self didFinishedEditAction:nil];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    if ([defaults objectForKey:@"username"]) {
        self.userNameTf.text = [defaults objectForKey:@"username"];
    }
    if ([defaults objectForKey:@"password"]) {
        self.passwordTf.text = [defaults objectForKey:@"password"];
    }
    
}

//忘记密码
- (IBAction)goToFindBackPasswordAction:(id)sender {
    FindPasswordViewController *findVC = (FindPasswordViewController *)[self.storyboard instantiateViewControllerWithIdentifier:@"FindPassword"];
    [self.navigationController pushViewController:findVC animated:YES];
}

- (IBAction)loginAction:(id)sender {
    
    NSString *userName = self.userNameTf.text;
    NSString *password = self.passwordTf.text;
    if ([userName length] == 0) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"
                                                        message:@"请输入手机号/邮箱"
                                                       delegate:nil
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles:nil];
        [alert show];
    } else if ([password length] == 0) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"
                                                        message:@"请输入密码"
                                                       delegate:nil
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles:nil];
        [alert show];
    } else {
        [self loginWithUserName:userName password:password];
    }
    
    [self.userNameTf resignFirstResponder];
    [self.passwordTf resignFirstResponder];
    
}



- (void)loginWithUserName:(NSString *)name password:(NSString *)password {
    
    [self loginWithUserName:name password:password roleFlag:-1];
}

- (void)loginWithUserName:(NSString *)name password:(NSString *)password roleFlag:(NSInteger)role {
    if (self.networkManager == nil) {
        self.networkManager = [[NetworkManager alloc] init];
    }
    NSMutableDictionary *param = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                           name,@"phone",
                           password,@"pwd", nil];
  
    if (param != nil) {
        [self.networkManager requestWithMethod:login parameter:param delegate:self];
        [self.HUD show:YES];
    }
}

- (IBAction)didFinishedEditAction:(id)sender {
    [self.userNameTf resignFirstResponder];
    [self.passwordTf resignFirstResponder];
}


//收集设备信息
- (void)sendDeviceInfo {
    UserInfo *user = [UserInfo instance];
    NSString *user_id = [user.info objectForKey:@"id"];
    
    NSString *pushId = @"";
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    if ([defaults valueForKey:@"token"]) {
        pushId = [defaults valueForKey:@"token"];
    }
    NSString *systemVersion = [UIDevice currentDevice].systemVersion;
    NSString *systemOS = [NSString stringWithFormat:@"IOS%@",systemVersion];
    
    NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:
                           pushId,@"pushId",
                           systemOS,@"systemOS",
                           user_id,@"userId",
                           nil];
    [self.networkManager requestWithMethod:sendDeviceInfo parameter:param delegate:nil];
    
}


//登录之后跳转
- (void)finishedLoginWithRole:(NSInteger)role {
    AppDelegate *dele = [AppDelegate sharedDelegate];
}


#pragma mark - NetworkManagerDelegate
- (void)network:(NetworkManager *)net methodId:(RequestMethodId)methodId didRequestFinishedWithResult:(id)data {
    [self.HUD hide:YES];
    
    if (methodId == login) {
        if ([data isKindOfClass:[NSDictionary class]]) {
            NSString * result = [data objectForKeyOrNil:@"result"];
            if([result isEqualToString:@"000"]){
                //保存用户信息
                
                NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
                NSString *usernameObj = [userDefaults stringForKey:@"username"];
                NSString *pwdObj = [userDefaults stringForKey:@"pwd"];
                
                if(usernameObj == nil){
                    [userDefaults setObject:self.userNameTf.text forKey:@"username"];
                    [userDefaults setObject:self.passwordTf.text forKey:@"pwd"];
                }
                //存储时，除NSNumber类型使用对应的类型外，其他的都是使用setObject:forKey:
                
                [userDefaults synchronize];
                
                NSDictionary *userInfo = [data objectForKeyOrNil:@"userinfo"];
                
                UserInfo *user = [UserInfo instance];
                user.info = [NSMutableDictionary dictionaryWithDictionary:userInfo];
                [self sendDeviceInfo];
                MainViewController *problemVC = (MainViewController *)[self.storyboard instantiateViewControllerWithIdentifier:@"MainViewController"];
//                UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:problemVC];
//                DDMenuController *menuVC = [[DDMenuController alloc] initWithRootViewController:navController];
                [self.navigationController pushViewController:problemVC animated:YES];
            } else {
                NSString *unicodeStr = [[data objectForKeyOrNil:@"resultinfo"]stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"
                                                                message:unicodeStr
                                                               delegate:self
                                                      cancelButtonTitle:@"确定"
                                                      otherButtonTitles:nil];
                [alert show];
 
            }
            
            
        }
    } 
}

- (void)network:(NetworkManager *)net methodId:(RequestMethodId)methodId didRequestFailedWithError:(NSError *)error {
    
    [self.HUD hide:YES];
    
    NSDictionary *errorInfo = error.userInfo;
    NSString *msg = [errorInfo objectForKeyOrNil:@"errorMsg"];
    if ([msg isKindOfClass:[NSNull class]] || [msg length] == 0) {
        if (methodId == login) {
            msg = @"登录失败，请稍后重试";
        }
        else if (methodId == sendDeviceInfo) {
            msg = @"，请稍后重试";
        }
        
    }
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                    message:msg
                                                   delegate:nil
                                          cancelButtonTitle:@"确定"
                                          otherButtonTitles:nil];
    [alert show];
}

#pragma mark -
#pragma mark keyboard notification
//监听键盘出现、消失和改变大小的事件。当切换至中文键盘，键盘高度改变时相应的改变键盘上方的控件
- (void)keyboardWillShow:(NSNotification*)notification {
    NSDictionary *userInfo = [notification userInfo];
    NSValue *animationDurationValue = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSTimeInterval animationDuration;
    [animationDurationValue getValue:&animationDuration];
    
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:animationDuration];
    
    CGRect frame = self.contentPreFrame;
    self.contentView.frame = CGRectMake(frame.origin.x, frame.origin.y - 150,
                                        frame.size.width, frame.size.height);
    
    
    [UIView commitAnimations];
}

- (void)keyboardWillHide:(NSNotification*)notification {
    NSDictionary *userInfo = [notification userInfo];
    NSValue *animationDurationValue = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSTimeInterval animationDuration;
    [animationDurationValue getValue:&animationDuration];
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:animationDuration];
    
//    CGRect frame = self.contentView.frame;
//    self.contentView.frame = CGRectMake(frame.origin.x, self.preOriginY,
//                                        frame.size.width, frame.size.height);
//    NSLog(@"&&&&&&&&** frame:%@",NSStringFromCGRect(self.contentView.frame));
    self.contentView.frame = self.contentPreFrame;
    
    [UIView commitAnimations];
}


@end
